package com.meixiang.http;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.AbsCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.activity.account.login.LoginActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 使用：https://github.com/jeasonlzy0216/OkHttpUtils
 * OkHttpUtils.post(Config.LOGIN).tag(this).params(params).execute(new HttpCallBack(this,"正在登录中..."){}
 * 请设置tag(用于取消请求)
 * <p/>
 * author:xiejingwen
 */
public abstract class HttpCallBack extends AbsCallback<JSONObject> {
    private Activity activity;
    private ProgressDialog dialog;

    /**
     * 请求时弹出等待dialog
     *
     * @param activity
     * @param message  传入展示信息（如：正在加载中...）
     */
    public HttpCallBack(Activity activity, String message) {
        this.activity = activity;
        dialog = initProgressDialog(activity, message);
    }

    /**
     * 该构造不弹出dialog
     *
     * @param activity
     */
    public HttpCallBack(Activity activity) {
        this.activity = activity;
    }

    /**
     * 非UI线程
     *
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject parseNetworkResponse(Response response) throws Exception {
        JSONObject jsonObject = new JSONObject(response.body().string());
        return jsonObject;
    }

    /**
     * 请求成功,响应200进入该方法
     *
     * @param isFromCache
     * @param jsonObject
     * @param request
     * @param response
     */
    @Override
    public void onResponse(boolean isFromCache, JSONObject jsonObject, Request request, @Nullable Response response) {
        if (activity==null){
            return;
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (jsonObject.optString("code").equals("0")) {
            JSONObject result;

            if(jsonObject.optJSONObject("result")==null){
                JSONArray array=jsonObject.optJSONArray("result");
                JSONObject object=new JSONObject();
                try {
                    object.put("list",array);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                result=object;
            }else{
                result=jsonObject.optJSONObject("result");
            }

            onSucceed(result,jsonObject.optString("code"), jsonObject.optString("message"));


        } else {
            onError(jsonObject.optString("code"), jsonObject.optString("message"));
        }
        isFromCache(isFromCache);
    }





    /**
     * 请求前
     *
     * @param request
     */
    @Override
    public void onBefore(BaseRequest request) {
        super.onBefore(request);
        if (activity==null){
            return;
        }
        if (dialog != null&&!dialog.isShowing()) {
            dialog.show();
        }
    }

    /**
     * 请求完成
     *
     * @param isFromCache
     * @param jsonObject
     * @param call
     * @param response
     * @param e
     */
    @Override
    public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
        super.onAfter(isFromCache, jsonObject, call, response, e);
        if (activity!=null&&activity.isFinishing()==false
                &&dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 请求异常
     *
     * @param isFromCache
     * @param call
     * @param response
     * @param e
     */
    @Override
    public void onError(boolean isFromCache, Call call, Response response, Exception e) {
        super.onError(isFromCache, call, response, e);
        if (activity==null){
            call.cancel();
        }else if (!Tool.isNetworkAvailable(activity)) {
            onError("","网络不可用");
        }else if (response != null) {
            if (response.code()==200){
                return;
            }
            if (response.code() == 400) {
                Log.e("error", "请求参数错误");
                onError("400","请求参数错误");
            } else if (response.code() == 401) {//跳转登录
                activity.startActivity(new Intent(activity, LoginActivity.class));
                if (MXApplication.mApp.hasLogin()){
                    MXApplication.mApp.logout();
                    MXApplication.mApp.fundLogout();
                }
                AbToastUtil.showToast(activity, "请去登录");
            } else if (response.code() == 403) {//供开发时提供信息
                Log.e("error", "服务器拒绝请求");
                onError("403","服务器拒绝请求");
            } else if (response.code() == 404) {
                Log.e("error", "地址错误");
                onError("404","地址错误");
            } else if (response.code() == 408) {
                Log.e("error", "请求超时");
                onError("408","请求超时");
            } else if (response.code() == 500) {
                Log.e("error", "服务器异常");
                onError("500","服务器异常");
            }
        }else if (e!=null){
            Log.e("e",e.toString());
            if (e.toString().equals("java.net.SocketTimeoutException")){
                onError("500","连接服务器超时");
            }else if (e.toString().equals("java.io.IOException: Canceled")){
                Log.e("e","取消请求");
            }else if (e.toString().equals("java.net.SocketException: Socket closed")){
                Log.e("e","关闭连接");
            }else {
                onError("500","连接服务器失败,请稍后重试");
            }
            if (e.getMessage()!=null){
                Log.e("e.getMessage",e.getMessage());
            }
        }
    }

    /**
     * 服务器返回成功
     *
     * @param result
     * @param code
     * @param message
     */
    public abstract void onSucceed(JSONObject result, String code, String message);

    /**
     * 服务器返回异常
     *
     * @param code
     * @param message
     */
    public abstract void onError(String code, String message);

    /**
     * 需要时复写 判断是不是获取缓存数据
     *
     * @param isFromCache
     */
    protected void isFromCache(boolean isFromCache) {

    }

    protected ProgressDialog initProgressDialog(Context context, String message) {
        ProgressDialog dialog = new ProgressDialog(context);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage(message);
        dialog.setCancelable(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                    dialog.dismiss();
                    OkHttpUtils.getInstance().cancelTag(activity);
                    return true;
                }
                return false;
            }
        });
        return dialog;
    }
}
